package com.jh.paymentchannel.service;

import cn.jh.common.utils.CommonConstants;
import com.jh.paymentchannel.payment.wechat.WechatConfig;
import com.jh.paymentchannel.payment.wechat.WechatPayRequest;
import com.jh.paymentchannel.payment.wechat.WechatUtil;
import com.jh.paymentchannel.util.DataUtils;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.milian.utils.HttpHelper;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
public class WechatTopupRequest implements RepaymentRequest {

    private static final Logger log = LoggerFactory.getLogger(WechatTopupRequest.class);

    @Autowired
    private Util util;

    @Override
    public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
                                            String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {

        log.info("调用wechat 通道开始=====================");
        Map<String, String> map = new HashMap<String, String>();
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("order_code", ordercode);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        log.info("查询订单信息结果result={}" + result);
        JSONObject jsonObject;
        JSONObject resultObj;
        try {
            jsonObject = JSONObject.fromObject(result);
            resultObj = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("查询订单信息出错");
            map.put("resp_code", "failed");
            map.put("channel_type", "milian_quick");
            map.put("resp_message", "没有该订单信息");
            return map;
        }
        uri = util.getServiceUrl("user", "error url request!");
        url = uri.toString() + "/v1.0/user/channelConfig/findByTerminalNo";
        /** 根据的用户手机号码查询用户的基本信息 */
        requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("terminalNo", resultObj.getString("terminalNo"));
        restTemplate = new RestTemplate();
        JSONObject resultObjs;
        try {
            result = restTemplate.postForObject(url, requestEntity, String.class);
            log.info("RESULT================" + result);
            jsonObject = JSONObject.fromObject(result);
            resultObjs = jsonObject.getJSONObject("result");
        } catch (Exception e) {
            log.error("==========/v1.0/user/channelConfig/findByTerminalNo 查询费率异常===========" + e);
            map.put("resp_code", "failed");
            map.put("resp_message", "查询费率异常");
            return map;
        }
        if (StringUtils.isBlank(resultObjs.getString("channelAppid")) ||
                StringUtils.isBlank(resultObjs.getString("channelSecret"))  ||
                StringUtils.isBlank(resultObjs.getString("channelMchId"))  ||
                StringUtils.isBlank(resultObjs.getString("channelKey")) ){
            map.put("resp_code", "failed");
            map.put("resp_message", "微信配置异常");
            return map;
        }
        WechatPayRequest wechatPayRequest = new WechatPayRequest();
        wechatPayRequest.setAppid(resultObjs.getString("channelAppid"));
        wechatPayRequest.setMch_id(resultObjs.getString("channelMchId"));
        wechatPayRequest.setBody(resultObjs.getString("channelPayName"));
        wechatPayRequest.setOut_trade_no(ordercode);
        wechatPayRequest.setTotal_fee(new BigDecimal(amount).multiply(new BigDecimal(100)).toString());
        wechatPayRequest.setNotify_url(notifyurl);

        TreeMap<String, Object> rquestMap = DataUtils.objToMap(wechatPayRequest);
        String xml = WechatUtil.generateSignedXml((Map) rquestMap, resultObjs.getString("channelKey"));
        String respResult = HttpHelper.doHttp(WechatConfig.SERVER_URL, HttpHelper.POST, "UTF-8", xml, "60000");
        if (!WechatUtil.sign(respResult,resultObjs.getString("channelKey"))){
            log.error("微信验签失败，=========="+respResult);
            map.put("resp_code", CommonConstants.FALIED);
            map.put("resp_message", "微信验签失败");
            return map;
        }
        Map stringMap = WechatUtil.xmlToMap(respResult);
        if ("SUCCESS".equals(stringMap.get("return_code"))) {
            log.error("微信通讯失败，==========");
            map.put("resp_code", CommonConstants.FALIED);
            map.put("resp_message", "微信通讯失败");
            return map;
        }
        if ("SUCCESS".equals(stringMap.get("result_code"))) {
            log.error("微信业务失败，=========="+stringMap.get("err_code")+"====="+stringMap.get("err_code_des"));
            map.put("resp_code", CommonConstants.FALIED);
            map.put("resp_message", (String)stringMap.get("err_code_des"));
            return map;
        }
        map.put("resp_code", CommonConstants.SUCCESS);
        map.put("resp_message", "成功");
        map.put("result",(String)stringMap.get("prepay_id"));

        return map;
    }

    @Override
    public Map<String, String> verifyBindCardRequest(HttpServletRequest request, String channelTag, String userId, String creditCardNumber, String brandId) throws Exception {
        return null;
    }
}
